<?php 
namespace App\Service;

defined('STDIN') or define('STDIN', fopen("php://stdin","r"));

use App\Jobs\LoginRobotJob;
use App\Lib\CacheKey;
use Illuminate\Support\Facades\Cache;
use waylaidwanderer\SteamCommunity\SteamCommunity;
use waylaidwanderer\SteamCommunity\Enum\LoginResult;
use App\Model\BotsModel;
use Exception;
use log;

class DologinService extends BaseService
{

	public static $instance = null;

	public static function getInstance()
	{
		if (self::$instance == null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * 机器人登陆
	 * @param  array $settings 机器人配置
	 * @return array
	 */
	public function dologin(array $settings)
	{
		try {
			$steam = new SteamCommunity($settings, dirname(__FILE__));
			$loginResult = $steam->doLogin();

			while ($loginResult != LoginResult::LoginOkay) {
				if ($loginResult == LoginResult::Need2FA) {
					if ($steam->mobileAuth() == null) {
						$authCode = $this->ask('Enter 2FA code: ');
						$steam->setTwoFactorCode($authCode);
					} else {
						$authCode = $steam->mobileAuth()->steamGuard()->generateSteamGuardCode();
						$steam->setTwoFactorCode($authCode);
						$this->writeLine('Generated Steam Guard code: ' . $authCode);
					}
					$loginResult = $steam->doLogin();

				} else if ($loginResult == LoginResult::NeedEmail) {
					$authCode = $this->ask('Enter Steam Guard code from email: ');
					$steam->setEmailCode($authCode);
					$loginResult = $steam->doLogin();
				} else if ($loginResult == LoginResult::NeedCaptcha) {
					$captchaCode = $this->ask('Enter captcha (' . $steam->getCaptchaLink() . '): ');
					$steam->setCaptchaText($captchaCode);
					$loginResult = $steam->doLogin();
				} else {
					break;
				}
				$this->writeLine("Login result: {$loginResult}.");
			}

			if (!$steam->isLoggedIn()) {
				throw new Exception('login robot failed');
			}

			$res = BotsModel::updateBotsLogin($settings['bot_id']);
			if (!$res) {
				Log::warning('update robot status failed, botid:'.$settings['bot_id']);
			}
			BotsService::getInstance()->setRobotCache($settings['username'], $steam);
			return true;
		} catch (Exception $e) {
			Log::warning('login robot failed, botid:'.$settings['bot_id']);
			return false;
		}
	}

	protected function writeLine($line)
	{
		echo $line.PHP_EOL;
	}

	protected function ask($prompt = '')
	{
		echo $prompt;
		return rtrim(fgets(STDIN), "\n");
	}

    /**
     * 获取存活机器
     * @return array
     */
    public function getLiveBotInfo(){
        $mBotLists = BotsModel::getFromAllLivingBotLists();
        $mBotListsColumn = array_column ($mBotLists, 'str_steam_account');
        $rBotLists = BotsModel::getResdisAllLivingBotLists();
        $botLists = array_intersect($mBotListsColumn, $rBotLists);

        if(empty($botLists)){
            foreach ($mBotLists as $key => $val){
                $currentQueue = 'LoginRobotJob_' . $val['client_no'];
                dispatch((new LoginRobotJob($val['id']))->onQueue($currentQueue)->delay(1));
            }

            return [];
        }

        shuffle($botLists);
        $rand = array_rand($botLists);
        $botsSteamAccount = str_replace('laravel:' . CacheKey::BOT_LIST_PRE,'',$botLists[$rand]);
        $botsInfo = BotsModel::getLivingBotBySteamAccount($botsSteamAccount);

        return $botsInfo;
    }
}